package common;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author ：daiyuanbao
 * @date ：Created in 2022/7/7 17:43
 * @description：
 */
public class SecondKillHandlder implements Runnable{

    private RedisTemplate redisTemplate;
    String goodsKey ; // 监视的key 当前秒杀商品的数量
    String userName;

    public SecondKillHandlder(String userName,String goodsKey,RedisTemplate redisTemplate) {
        this.userName = userName;
        this.goodsKey = goodsKey;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void run() {
        while (true) {
            try {
                // watch 监视一个key，当事务执行之前这个key发生了改变，事务会被打断
                redisTemplate.watch(goodsKey);
                Integer  currentGoodsCount = (Integer)redisTemplate.opsForValue().get(goodsKey); // 当前剩余商品数量
                if(currentGoodsCount==null){
                    System.out.println("秒杀未开始！");
                }
                if (currentGoodsCount <= 0) {
                    System.out.println("商品已抢完，" + userName + "---> 抢购失败 XXX");
                    break;
                }
                redisTemplate.multi();// 开启事务
                redisTemplate.opsForValue().decrement(goodsKey,1);
                Object o1 = redisTemplate.opsForValue().get(goodsKey);
                List<Object> exec = redisTemplate.exec(); // 执行事务
                if (CollectionUtils.isEmpty(exec)) {
                    System.out.println(userName + "---> 抢购失败，继续抢购");
                    Thread.sleep(1);
                } else {
                    exec.forEach(
                            succ -> {
                                String succStr =
                                        userName
                                                + "===========================> 抢购到第【"
                                                + ((100 - currentGoodsCount) + 1)
                                                + "】份商品，该商品剩余："
                                                + succ.toString();
                                System.out.println(succStr);
                                redisTemplate.opsForValue().set("goodsResult:" + userName, succStr); // 业务代码，处理抢购成功
                            });
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
